package secondriver.springsubway.example.jta;

import java.sql.Connection;
import java.sql.SQLException;

import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.atomikos.icatch.jta.UserTransactionManager;
import com.atomikos.jdbc.AtomikosDataSourceBean;

public class TestAtomikos1 {

	public static ApplicationContext ctx;

	@BeforeClass
	public static void beforeClass() {
		ctx = new ClassPathXmlApplicationContext(
				"classpath:integration/spring-jta.xml");
	}

	public static void afterClass() {
		ctx = null;
	}

	@Test
	public void test1() {
		exe("abc", "abc");
	}

	@Test
	public void test2() {
		exe("123=", "123");
	}

	public void exe(String av, String bv) {

		AtomikosDataSourceBean adsA = (AtomikosDataSourceBean) ctx.getBean("a");
		AtomikosDataSourceBean adsB = (AtomikosDataSourceBean) ctx.getBean("b");
		Connection connA;
		Connection connB;
		UserTransactionManager utm = (UserTransactionManager) ctx
				.getBean("atomikosUserTransactionManager");
		try {
			utm.begin();
			connA = adsA.getConnection();
			connB = adsB.getConnection();
			connA.prepareStatement(
					"insert into jta_temp (value) values('" + av + "')")
					.execute();
			connB.prepareStatement(
					"insert into jta_temp (value) values('" + bv + "')")
					.execute();
			utm.commit();
		} catch (SQLException | NotSupportedException | SystemException
				| SecurityException | IllegalStateException | RollbackException
				| HeuristicMixedException | HeuristicRollbackException e) {
			e.printStackTrace();
			try {
				utm.rollback();
			} catch (IllegalStateException | SecurityException
					| SystemException e1) {
				e1.printStackTrace();
			}
		}
	}
}
